package com.lightsaber.trade.cloth.web.dataimport;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.Namespace;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springside.modules.orm.Page;

import com.lightsaber.trade.core.web.BaseAction;
import com.lightsaber.trade.cloth.entity.dataimport.Dataimport;
import com.lightsaber.trade.cloth.entity.dataimport.DataimportInterfaceType;
import com.lightsaber.trade.cloth.entity.dataimport.DataimportStatus;
import com.lightsaber.trade.cloth.entity.dataimport.Events;
import com.lightsaber.trade.cloth.service.dataimport.DataimportManager;
import com.lightsaber.trade.cloth.service.dataimport.DataimportService;
import com.lightsaber.trade.cloth.service.dataimport.EventsManager;

@Namespace("/dataimport")
public class DataimportAction extends BaseAction {

    final static Logger log = LoggerFactory.getLogger(DataimportAction.class);

    // ****************** Autowired *****************START
    @Autowired
    private transient DataimportManager dataimportManager;

    @Autowired
    private transient DataimportService dataimportService;

    @Autowired
    private transient EventsManager eventsManager;

    // ****************** Autowired *****************END

    // ****************** Page parameters *****************START
    private boolean search;
    private String dataimportId;

    private Dataimport dataimport = new Dataimport();

    // private EventsManager eventsManager = new EventsManager();

    private Events events = new Events();

    private String runAtDate = "";
    private String runAtHour = "";
    private String runAtMin = "";

    @Value(value = "#{appProperties['dataimport.page.size']}")
    private String PAGE_SIZE;

    @Value(value = "#{appProperties['dataimport.interface.file.path']}")
    private String INF_PATH;

    @Value(value = "#{appProperties['dataimport.interface.importer']}")
    private String INF_IMPORTER;

    @Value(value = "#{appProperties['dataimport.interface.importer.batchload.num']}")
    private String INF_BATCH_NUM;

    @Value(value = "#{appProperties['dataimport.interface.importer.programme.launch.ver']}")
    private String INF_LAUNCH_VER_DEFAULT;

    private Page<Dataimport> page;
    // ****************** Page parameters *****************END
    private static final long serialVersionUID = -6133932528005700711L;

    @Override
    public String execute() {
        return list();
    }

    public String list() {
        if (search) {
            if (page == null) {
                page = new Page<Dataimport>(Integer.valueOf(PAGE_SIZE));
            } else {
                page.setPageSize(Integer.valueOf(PAGE_SIZE));
            }

            if (!page.isOrderBySetted()) {
                page.setOrderBy("id");
                page.setOrder(Page.ASC);
            }

            dataimportManager.findPage(dataimport, page);

        } else {
            dataimport = null;// 点击clear按钮,清空页面
        }

        return SUCCESS;
    }

    /**
     * 定义在input()前执行
     */
    public void prepareInput() throws Exception {

    }

    @Override
    public String input() throws Exception {
        if (dataimportId != null) {
            dataimport = dataimportManager.get(dataimportId);
            return "details";
        } else {
            dataimport = new Dataimport();
            return INPUT;
        }
    }

    public String save() throws Exception {

        if (validateSave() == false) {
            // log.error("ERROR in validateSave");
            return INPUT;
        }

        DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm");
        DateFormat dfp = new SimpleDateFormat("yyyyMMdd_HHmmss_");
        Date runAtTimestamp = new Date();
        File saveFile;
        String saveFileName = "";
        Calendar cal = Calendar.getInstance();
        saveFileName = dfp.format(cal.getTime());

        // saveFileName = current date/time + jobName without space + original
        // file name
        saveFileName = saveFileName + dataimport.getJobName().replaceAll(" ", "") + "_"
                + dataimport.getFileFileName();
        saveFile = new File(INF_PATH + saveFileName);

        try {
            if (dataimport.getFile() != null) {
                FileUtils.copyFile(dataimport.getFile(), saveFile);
                dataimport.setInterfaceFilePath(saveFile.getAbsolutePath());
            }
            runAtTimestamp = df.parse(runAtDate + " " + runAtHour + ":" + runAtMin);
            // dataimport.setRunAt(df.parse(runAtDate+" "+runAtHour+":"+runAtMin));
            dataimport.setRunAt(runAtTimestamp);

        } catch (Exception ex) {
            if (saveFile.isFile()) {
                saveFile.delete();
            }
            addActionError(ex.getMessage());
            log.error("ERROR in copy file, msg:" + ex.getMessage());
            return INPUT;
        }

        // add record to jcrontab.events
        DateFormat cron_yyyy = new SimpleDateFormat("yyyy");
        DateFormat cron_MM = new SimpleDateFormat("MM");
        DateFormat cron_dd = new SimpleDateFormat("dd");
        DateFormat cron_HH = new SimpleDateFormat("HH");
        DateFormat cron_mm = new SimpleDateFormat("mm");

        String cronYear = cron_yyyy.format(runAtTimestamp);
        String cronMonth = cron_MM.format(runAtTimestamp);
        String cronDayOfMonth = cron_dd.format(runAtTimestamp);
        String cronHour = cron_HH.format(runAtTimestamp);
        String cronMinute = cron_mm.format(runAtTimestamp);

        events.setYear(cronYear);
        events.setMonth(cronMonth);
        events.setDayOfMonth(cronDayOfMonth);
        events.setHour(cronHour);
        events.setMinute(cronMinute);
        events.setSecond("0");
        events.setDayOfWeek("*");
        events.setBusinessDays("0");
        events.setExtraInfo(INF_BATCH_NUM + " " + dataimport.getInterfaceType() + " "
                + INF_LAUNCH_VER_DEFAULT);
        events.setTask(INF_IMPORTER);

        // [01] auto-generated ID is obtained after save record to EVENTS
        eventsManager.save(events);

        // [02] add auto-generated events's ID to Dataimport record and save to
        // MHPP_DATAIMPORT_JOB, and save the
        dataimport.setEventsId(events.getId());
        dataimportManager.save(dataimport);

        // [03] append auto-generated MHPP_DATAIMPORT_JOB UUID to EVENTS
        // extrainfo
        events.setExtraInfo(dataimport.getId() + " " + events.getExtraInfo());
        eventsManager.save(events);

        addActionMessage(getText(PROCESSED_SUCCESS));

        return "details";
    }

    public boolean validateSave() {
        // interface SRS
        if (StringUtils.equalsIgnoreCase(dataimport.getInterfaceType(),
                DataimportInterfaceType.WebServiceSRS.name())) {
            dataimport.setFile(null);

            // interface IVE/TRS
        } else {
            if (dataimport.getFile() == null) {
                addActionError("Interface File is missing.");
                log.error("Interface File is missing");
                return false;
            }
        }

        return true;
    }

    public String convertFilename(final String filename) {
        File file = new File(filename);
        return file.getName();
    }

    public static Map<String, String> getStatusList() {
        return DataimportStatus.list();
    }

    public static Map<String, String> getInterfaceTypeList() {
        return DataimportInterfaceType.list();
    }

    public String getInterfaceTypeName(final DataimportInterfaceType type) {
        return DataimportInterfaceType.getNameByType(type);
    }

    public String getRunAtDateTitle() {
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

        Calendar currentDate = Calendar.getInstance();
        String dateNow = sdf.format(currentDate.getTime());

        return "from:" + dateNow;
    }

    // ******************** Bean *******************START
    public String getRunAtDate() {
        if (dataimport.getRunAt() != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
            this.runAtDate = sdf.format(dataimport.getRunAt());
        }
        return runAtDate;
    }

    public void setRunAtDate(final String runAtDate) {
        this.runAtDate = runAtDate;
    }

    public String getRunAtHour() {
        if (dataimport.getRunAt() != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("HH");
            this.runAtHour = sdf.format(dataimport.getRunAt());
        }
        return runAtHour;
    }

    public void setRunAtHour(final String runAtHour) {
        this.runAtHour = runAtHour;
    }

    public String getRunAtMin() {
        if (dataimport.getRunAt() != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("mm");
            this.runAtMin = sdf.format(dataimport.getRunAt());
        }
        return runAtMin;
    }

    public void setRunAtMin(final String runAtMin) {
        this.runAtMin = runAtMin;
    }

    public void setSearch(final boolean search) {
        this.search = search;
    }

    public boolean getSearch() {
        return search;
    }

    public String getDataimportId() {
        return dataimportId;
    }

    public void setDataimportId(final String dataimportId) {
        this.dataimportId = dataimportId;
    }

    public Dataimport getDataimport() {
        return dataimport;
    }

    public void setDataimport(final Dataimport dataimport) {
        this.dataimport = dataimport;
    }

    public Page<Dataimport> getPage() {
        return page;
    }

    public void setPage(final Page<Dataimport> page) {
        this.page = page;
    }

    public DataimportManager getDataimportManager() {
        return dataimportManager;
    }

    public void setDataimportManager(final DataimportManager dataimportManager) {
        this.dataimportManager = dataimportManager;
    }

    /*
     * public ParamService getParamService() { return paramService; }
     */
    public DataimportService getDataimportService() {
        return dataimportService;
    }

    // ******************** Bean *******************END
}
